package cn.com.server.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.Random;
import java.util.UUID;

/**
 * 
 * @author orange
 *
 */
public class FileUtils {
	/**
	 * 文件文末追加内容
	 * 
	 * @param filePath
	 * @param content
	 */
	public static boolean appendMethodFile(String filePath, String content) {
		try {
			// 打开一个随机访问文件流，按读写方式
			RandomAccessFile randomFile = new RandomAccessFile(filePath, "rw");
			// 文件长度，字节数
			long fileLength = randomFile.length();
			// 将写文件指针移到文件尾。
			randomFile.seek(fileLength);
			randomFile.writeBytes(content);
			randomFile.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 文件前追加内容
	 * 
	 * @param filePath
	 * @param content
	 */
	public static boolean appendFirstFile(String filePath, String content) {
		int MAX_DATA_BLOCK = 4096;
		int index = filePath.lastIndexOf(File.separatorChar);
		//追加后临时文件
		String destFile = filePath.substring(0, index) + File.separatorChar + UUID.randomUUID().toString();
		try {
			File file = new File(filePath);
			if (!file.exists()) {
				return false;
			}
			//头部追加
			File dest = new File(destFile);
			OutputStream out = new FileOutputStream(destFile);
			out.write(content.getBytes(), 0,content.getBytes().length);
			out.flush();
			//源文件内容
			RandomAccessFile in = new RandomAccessFile(filePath, "r");
			long inputLen = in.length();
			long offSet = 0;
			while (inputLen - offSet > 0) {
				byte[] cache = null;
				if(inputLen-offSet>=MAX_DATA_BLOCK) {
					cache = new byte[MAX_DATA_BLOCK];
				}else {
					cache = new byte[(int)(inputLen-offSet)];
				}
				in.read(cache);
				offSet = offSet + MAX_DATA_BLOCK;
				out.write(cache,0,cache.length);
				out.flush();
			}
			in.close();
			out.close();
			file.delete();
			dest.renameTo(new File(filePath));
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			if (new File(destFile).exists()) {
				new File(destFile).delete();
			}
			return false;
		}
	}

	/**
	 * 减少文末内容
	 * 
	 * @param filePath
	 * @param length
	 *            return 文末内容
	 */
	public static String subtractMethodFile(String filePath, long length) {

		int MAX_DATA_BLOCK = 4096;
		File file = new File(filePath);
		String path = file.getPath();
		int index = path.lastIndexOf(File.separatorChar);
		if (!file.exists()) {
			return "";
		}
		String destFile = path.substring(0, index) + File.separatorChar + UUID.randomUUID().toString();

		try {

			File dest = new File(destFile);
			OutputStream out = new FileOutputStream(destFile);

			String str = "";
//			InputStream in = new FileInputStream(filePath);
			RandomAccessFile in = new RandomAccessFile(filePath, "r");
			str = readLastLine(file,length);
			long inputLen = in.length() - length;
			long offSet = 0;
			while (inputLen - offSet > 0) {
				byte[] cache = null;
				if(inputLen-offSet>=MAX_DATA_BLOCK) {
					cache = new byte[MAX_DATA_BLOCK];
				}else {
					cache = new byte[(int)(inputLen-offSet)];
				}
				in.read(cache);
				offSet = offSet + MAX_DATA_BLOCK;
				out.write(cache, 0,cache.length);
				out.flush();
			}
			in.close();
			out.close();
			file.delete();
			dest.renameTo(new File(filePath));
			return str;
		} catch (Exception e) {
			e.printStackTrace();
			if (new File(destFile).exists()) {
				new File(destFile).delete();
			}
			return "";
		}
	}
	
	/**
	 * 减少文首内容
	 * 
	 * @param filePath
	 * @param length
	 *            return 文末内容
	 */
	public static String subtractFirstFile(String filePath, long length) {

		int MAX_DATA_BLOCK = 4096;
		File file = new File(filePath);
		String path = file.getPath();
		int index = path.lastIndexOf(File.separatorChar);
		if (!file.exists()) {
			return "";
		}
		String destFile = path.substring(0, index) + File.separatorChar + UUID.randomUUID().toString();

		try {

			File dest = new File(destFile);
			OutputStream out = new FileOutputStream(destFile);

			String str = "";
//			InputStream in = new FileInputStream(filePath);
			RandomAccessFile in = new RandomAccessFile(filePath, "r");
			str = readFirstLine(file,length);
			long inputLen = in.length()-length;
			in.seek(length);
			long offSet = 0;
			while (inputLen - offSet > 0) {
				byte[] cache = null;
				if(inputLen-offSet>=MAX_DATA_BLOCK) {
					cache = new byte[MAX_DATA_BLOCK];
				}else {
					cache = new byte[(int)(inputLen-offSet)];
				}
				in.read(cache);
				offSet = offSet + MAX_DATA_BLOCK;
				out.write(cache, 0,cache.length);
				out.flush();
			}
			in.close();
			out.close();
			file.delete();
			dest.renameTo(new File(filePath));
			return str;
		} catch (Exception e) {
			e.printStackTrace();
			if (new File(destFile).exists()) {
				new File(destFile).delete();
			}
			return "";
		}
	}

	public static String readLastLine(File file,long length){
		try {
			if (!file.exists() || file.isDirectory() || !file.canRead()) {
				return "";
			}
			RandomAccessFile raf = null;
			raf = new RandomAccessFile(file, "r");
			long len = raf.length();
			if (len == 0L) {
				raf.close();
				return "";
			} else {
				long pos = len - length;
				if(pos>0) {
					raf.seek(pos);
				}
				if (pos <= 0) {
					raf.seek(0);
				}
				byte[] bytes = new byte[(int) (len - pos)];
				raf.read(bytes);
				String md5 = new String(bytes);
				raf.close();
				return md5;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} 
	}
	
	public static String readFirstLine(File file,long length){
		try {
			if (!file.exists() || file.isDirectory() || !file.canRead()) {
				return "";
			}
			RandomAccessFile raf = null;
			raf = new RandomAccessFile(file, "r");
			long len = raf.length();
			if (len == 0L) {
				raf.close();
				return "";
			} else {
				long pos = 0;
				if(length>len) {
					length = len;
				}
				raf.seek(pos);
				byte[] bytes = new byte[(int) (length)];
				raf.read(bytes);
				String md5 = new String(bytes);
				raf.close();
				return md5;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} 
	}
	
	/**
	 * 随机补足或者截取 length位字符
	 * @param str
	 * @param length
	 * @return
	 */
	public static String Random(String str, long length) {
		String rstr =  "0123456abcdefghijklmnopqrstuvwxyZABCDEFGHIJKLMNOPQRSTUVWXYZ";
		Random random = new Random();
		String productNumber =str;
		if(productNumber.length()<length) {
				productNumber = productNumber + "/";
			for(int i = 1;i<length-str.length();i++) {
				productNumber = productNumber+rstr.charAt(random.nextInt(rstr.length()));
			}
		}
		if(productNumber.length()>length) {
			productNumber = productNumber.substring(0,(int)(length-1));
		}
		return productNumber;
	}
}
